package cn.szzsi.common.file;

import cn.szzsi.core.CoreConfig;
import cn.szzsi.core.file.FileMsg;
import cn.szzsi.core.file.Files;
import cn.szzsi.core.file.FilesService;
import cn.szzsi.core.file.QiniuUtil;
import com.jfinal.core.JFinal;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class UploadFileUtil {


    /**
     *
     */
    public static String newuploadfile(String shopId,File resFile) {
        String suffix= resFile.toString().substring(resFile.toString().lastIndexOf("."));
        String originalNamer=resFile.toString().substring(resFile.toString().lastIndexOf(File.separator)+1);//原文件名
        String fileName=getFileName(shopId,suffix,originalNamer);
        Boolean backBoolean= QiniuUtil.qu.upload(resFile.toString(),fileName);//文件传到七牛云
        if(backBoolean){
            String prefix=fileName.substring(fileName.indexOf("/")+1,fileName.lastIndexOf("/"));//前缀(201703格式)
            String pid="";
            //查看该店铺是否存在该文件夹
            Files files = cn.szzsi.core.file.Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix);
            if(files ==null){
                FilesService.service.saveFiles(shopId,"0",prefix,0,0,"",0L);
            }
            pid = Files.dao.getByShopIdAndTypeAndUrl(shopId,0,prefix).getStr("id");//父级ID
            FilesService.service.saveFiles(shopId,pid, CoreConfig.p.get("qiniu.url")+fileName,1,0,originalNamer,resFile.length());
        }
        resFile.delete();//上传成功后将本地服务器文件删除
        return CoreConfig.p.get("qiniu.url")+fileName;
    }



    /**
     * 根据shopId获取图片名称
     * @param shopId
     */
    public static String getFileName(String shopId,String suffix,String originalNamer){
        if(StrKit.notBlank(originalNamer)){
            return shopId+"/"+ DateFormatUtils.format(new Date(),"yyyyMM")+"/"+ originalNamer;
        }else{
            return shopId+"/"+ DateFormatUtils.format(new Date(),"yyyyMM")+"/"+ StrKit.getRandomUUID()+suffix;
        }

    }
}
